#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

#include "utils.h"

void str2Argv(char** argv, const char* str, int maxLines) {
    int cursor = 0, line = 0, j = 0;
    bool isStr = false;
    while ('\0' != str[cursor]) {
        if ('"' == str[cursor]) {
            isStr = !isStr;
        } else  if (!isStr && ' ' == str[cursor]) {
            if (0 != j) {
                argv[line][j] = '\0';
                if (line < maxLines - 1) {
                    line++;
                }
                else {
                    break;
                }
                j = 0;
            }
        } else {
            *((unsigned char *)(&argv[line][j])) = *((unsigned char *)(&str[cursor]));
            j++;
        }
        cursor++;
    }
    argv[line][j] = '\0';

    //for(int i = 0; i < maxLines; i ++)BOSE_LOGI("ryan: str2Argv(), arg[%d]=%s",i, argv[i]);
}

int bose_file_read(const char *path, void *buffer, int max_file_len) {
    int fd = -1;
    int rd = -1;

    fd = open(path, O_RDONLY);
    if (fd == -1) {
        BOSE_LOGE("ryan: open failed! path=%s\n", path);
        return -1;
    }

    rd = read(fd, buffer, max_file_len);
    if (rd == -1) {
        BOSE_LOGE("ryan: read failed, rd=%d\n", rd);
        goto ERROR;
    }

    close(fd);

    return 0;

ERROR:
    close(fd);
    return -1;
}

int bose_file_write(const char *path, const char *value, int max_file_len) {
    int fd = -1;
    int rd = -1;

    fd = open(path, O_WRONLY | O_CREAT , S_IROTH | S_IRGRP | S_IRUSR | S_IWUSR);
    if (fd == -1) {
        BOSE_LOGE("ryan: open failed! path=%s\n", path);
        return -1;
    }

    rd = write(fd, value, max_file_len);
    if (rd == -1) {
        BOSE_LOGE("ryan: write failed, rd=%d\n", rd);
        goto ERROR;
    }

    close(fd);

    return 0;

ERROR:
    close(fd);
    return -1;
}

